//获取应用实例
var fun_md5 = require('../utils/md5.js')
var app = getApp()
import * as Api from '../utils/api.js'
Page({
  data: {
    componentSearch: '',
    contactMobile: '　　　　　　',
    testName: '',
    statement: {},
    statementStatus: false,
    themeColors: '',
    memberAudit: true,
    miniAppsEntrance: true,
    miniAppsEntranceMessage: "商家小程序未开通",
    onlineService:false,
    cartCounts: 0,
    orderCounts: 0,
    vinSearch: null,
    oemSearch: null,
    basicMall: false,
    latitude: '',
    longitude: '',
    mainBanner: '',
    count: 0,
    userInfo:null,
    pageCount: '',
    page: 0,
    keyword: '',
    model: false,
    addressValue: '',
    addressList: null,
    hasGoneAway: false,
    indexIcon: [
      {
        icon: '../image/6.png',
        text: '购物车',
        color: '#FF7E21',
        url: '../core/carts/carts',
        basicMall: false,
      },
      {
        icon: '../image/8.png',
        text: '导航到店',
        color: '#29B6F6',
        url: '../location/location',
        basicMall: true
      },

      {
        icon: '../image/34.png',
        text: '客服',
        color: '#09BB07',
        url: '../phone/phone',
        basicMall: true
      },
      {
        icon: '../image/10.png',
        text: '我的',
        color: '#26A69A',
        url: '../core/me/me',
        basicMall: true
      },
    ]
  },
  telContactMobile() {
    wx.makePhoneCall({
      phoneNumber: this.data.contactMobile //仅为示例，并非真实的电话号码
    })
  },
  goOemFilter() {
 
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })

      // if (app.globalData.userId === null) {
      //   wx.navigateTo({
      //     url: '../core/login/login',
      //   })
      //   return
      // }

      wx.navigateTo({
        url: '../example/query/query',
      })
    }

  },
  handleInpue(e) {
    this.setData({
      keyword: e.detail.value
    })
    if (!this.data.keyword){
      this.addressList()
    }
  },
  closeKeywordFn() {
    this.setData({
      keyword: ''
    })
    this.addressList()
  },
  // 地址列表
  addressList(replace = false) {
    console.log(55)
    console.log(app.globalData.userId)

    let self = this
    let url = app.globalData.baseUrl1 + '/merchant/front/shop/list'

    let data = {
      page: this.data.page,
      pageSize: 20,
      keyword: self.data.keyword,
      merchantId: app.globalData.merchant.merchantId,
    }
    //'0cc601c92d55ee9bac0a62c3bcbbbee3'
    let callBack = (res) => {
      console.log(res)

      if (res == null) {

        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        console.log('获取数据失败')
        return;
      }

      if (res.data.status == 200) {
        if (res.data.data.page.page) {

        }
        console.log(res)
        if (replace && res.data.data.shopList.length > 0) {
          let attr = this.data.addressList

          this.setData({
            addressList: attr.concat(...res.data.data.shopList)
          })
          console.log(this.data.addressList)
          return
        } else if (replace && !res.data.data.shopList.length) {
          this.setData({
            notMore: false,
          })
          return
        }
        this.setData({
          addressList: res.data.data.shopList,
          pageCount: res.data.data.page.pageCount

        })
      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  searchScrollLower() {
    if (this.data.notMore) {
      this.setData({
        page: ++this.data.page
      })
      this.addressList(true)
    }
  },

  goVinFilter() {
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })

      if ((this.data.memberAudit || app.globalData.merchant.mustLogin) && app.globalData.userId === null) {
        wx.navigateTo({
          url: '../core/login/login',
        })
        return
      }
      wx.navigateTo({
        url: '../example/querycar/querycar',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }



  },
  openLoacl() {
    let self = this
    console.log('打开定位')
    console.log(parseFloat(self.data.latitude))
    console.log(parseFloat(self.data.longitude))

    wx.openLocation({
      latitude: parseFloat(self.data.latitude),
      longitude: parseFloat(self.data.longitude),
      name: self.data.name,
      scale: 28
    })
  },
  goFilterType() {

    // wx.navigateTo({
    //   url: '../core/vin/vin',
    // })
    // return
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
     
      if ((this.data.memberAudit || app.globalData.merchant.mustLogin) && app.globalData.userId === null) {
        wx.navigateTo({
          url: '../core/login/login',
        })
        return
      }
      let url = '../example/filter_type/filter_type'
      wx.navigateTo({
        url: url,
      })
    }


  },

  openLocation(e) {
    console.log(e)
    wx.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.latitude),
      longitude: parseFloat(e.currentTarget.dataset.longitude),
      name: e.currentTarget.dataset.name,
      address: e.currentTarget.dataset.address,
      scale: 28
    })
  },
  closeAddress() {
    console.log(555)
    this.setData({
      model: false,
      keyword: '',
      hasGoneAway: false
    })
    this.closeKeywordFn()
  },



  goMenu(e) {

    let self = this

    if (e.currentTarget.dataset.url == '../phone/phone') {



      // wx.makePhoneCall({
      //   phoneNumber: app.globalData.merchant.contactMobile //仅为示例，并非真实的电话号码
      // })



      return
    }
    console.log(app.globalData.userInfo)
    wx.getUserInfo({
      success: (res) => {
        console.log(res)
        self.setData({
          hasGoneAway: true
        })
        app.globalData.userInfo = res.userInfo
        if (app.globalData.userInfo) {
          self.setData({ hasGoneAway: true })
          if ((e.currentTarget.dataset.url == '../core/me/me' || e.currentTarget.dataset.url == '../core/carts/carts') && app.globalData.userId === null) {
            wx.navigateTo({
              url: '../core/login/login',
            })
            return
          }
          // if (e.currentTarget.dataset.url === '../location/location') {
          //   self.openLoacl()
          //   return
          // }
          if (e.currentTarget.dataset.url === '../location/location') {
            console.log(this.data.model)
            console.log(this.data.addressList.length)
            this.setData({ hasGoneAway: false })
            if (!this.data.addressList.length) {
              wx.showToast({
                title: '没有店铺地址',
                icon: 'none',

              })
              return
            }

            this.setData({
              model: true,
              listHeight: this.data.addressList.length * 90
            })
            // this.openLoacl()
            return
          }
          wx.navigateTo({
            url: e.currentTarget.dataset.url
          })
        }

      }
    })
    

    console.log(this.data.hasGoneAway)
    
  },
  loginOut() {
    let self = this
    let url = app.globalData.baseUrl1 + '/auth/user/loginout'
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId
    }
    let callBack = (res) => {
      console.log('退出登录', res)
      if (res == null) {
        console.log("网络请求错误1！");
        return;
      }
      if (res.data.status != 200) {
        wx.showModal({
          title: res.data.message,
          content: '',
          showCancel: false,
          cancelColor: '',
          confirmColor: '',
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        })

        return;
      }
      if (res.data.status == 200) {
        app.globalData.token = null
        app.globalData.userId = null
        wx.showModal({
          title: '账号已冻结，请联系管理员',
          content: '',
          showCancel: false,
          cancelColor: '',
          confirmColor: '',
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        })

      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  toastViewClose() {
    app.globalData.statementStatus = false
    this.setData({
      statementStatus: app.globalData.statementStatus
    })
  },
  changeName(e) {
    this.setData({
      testName: e.detail.value
    })
  },
  getNameByUserId() {
    if (app.globalData.token === null || app.globalData.userId === null) {
      wx.navigateTo({
        url: '../core/login/login',
      })
      return
    }

    let self = this
    let url = app.globalData.baseUrl1 + '/supplier/info/byuser'
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
    }
    let callBack = (res) => {

      if (app.globalData.token === null) {
        wx.navigateTo({
          url: '../core/login/login',
        })
        return
      }
      if (res == null) {

        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        self.setData({
          count: self.data.count + 1
        })
        if (self.data.count < 50) { self.getNameByUserId() }
        return;
      }

      if (res.data.status == 200) {


      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  getOrderCount() {
    if (app.globalData.userId === null) {
      return
    }
    let self = this
    let url = app.globalData.baseUrl1 + '/user/cart/count'
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
    }
    let callBack = (res) => {


      if (res == null) {

        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        self.setData({
          count: self.data.count + 1
        })
        if (self.data.count < 50) {
          self.getNameByUserId()
        }
        return;
      }

      if (res.data.status == 200) {

        console.log('订单购物车数量', res)
        self.setData({
          cartCounts: parseInt(res.data.data.cartCounts),
          orderCounts: parseInt(res.data.data.orderCounts)
        })
        console.log(this.data.cartCounts)
      }
    }
    Api.reqFormPost(url, data, callBack)
  },


  initIndex() {
    let self = this;
    console.log(111, app.globalData.merchant)
    //消息推送
    // setTimeout(() => {
    wx.getStorage({
      key: 'themeColors',
      success: function (res) {
        self.setData({
          themeColors: res.data
        })
      }
    })
    

   
    //消息推送
    self.setData({
      statement: app.globalData.statement,
      statementStatus: app.globalData.statementStatus
    })
    let indexIcon = self.data.indexIcon
    indexIcon[0].basicMall = app.globalData.merchant.basicMall
    indexIcon[2].basicMall = app.globalData.merchant.onlineService
    
    
    let mainBanner = app.globalData.merchant.mainBanner.split(",")
    self.setData({
      indexIcon: indexIcon,
      contactMobile: app.globalData.merchant.contactMobile,
      vinSearch: app.globalData.merchant.vinSearch,
      mainBanner: mainBanner,
      latitude: app.globalData.merchant.latitude,
      longitude: app.globalData.merchant.longitude,
      miniAppsEntrance: app.globalData.merchant.miniAppsEntrance,
      memberAudit: app.globalData.merchant.memberAudit,
      themeColors: app.globalData.merchant.themeColors,
      componentSearch: app.globalData.merchant.componentSearch
    })
    wx.setNavigationBarTitle({
      title: app.globalData.merchant.merchantName
    })
    //订单数量&购物车数量
    self.getOrderCount()

    if (app.globalData.userStatus === 'USER_CHECK_SUCCEED') {
      wx.setStorageSync('userId', app.globalData.userId);//userId       
    } else if (app.globalData.userStatus === 'USER_CHECK_FAILED') {
      self.loginOut()
    }
    // }, 500);



  },
  onUnload: function () {
    // console.log('页面卸载')
  },
  onHide: function () {

  },
  onReady: function () {

  },
  onShow: function () {

    if (app.globalData.merchant === null) {
      return
    }
    let self = this
    this.setData({
      hasGoneAway: false,
      userInfo: app.globalData.userInfo
    })
    wx.getUserInfo({
      success:(res) => {
        console.log(res)
      }
    })
    console.log(this.data.userInfo)
    console.log('获取信息')
    this.initIndex()
    // 获取多地址列表
    this.addressList()
  },
  searchAddressFn() {
    this.addressList()
  },
  onLoad: function () {
    let self = this

    //商城小程序服务是否开通
    if (!app.globalData.miniAppsEntrance) {
      app.globalData.formStatus = true
      self.setData({
        miniAppsEntrance: app.globalData.miniAppsEntrance,
        miniAppsEntranceMessage: app.globalData.miniAppsEntranceMessage
      })
      return
    }


    
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow);
      return
    }

    wx.getStorage({
      key: 'merchant',
      success: function (res) {
        let merchant = JSON.parse(res.data)
        console.log(merchant)
        app.globalData.merchant = merchant

      }, fail() {
      }
    })



    app.globalData.lastTapTime = 0
    wx.showShareMenu({
      withShareTicket: true
    })
    this.setData({

      windowWidth: app.globalData.windowWidth
    })
  }
})
